package com.wshl.aijiuunion.controller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.MainActivity;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.view.bean.BindPhoneBean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.view.widget.Loadingdialog;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/11/14 0014
 */
public class BindPhoneActivity extends AppCompatActivity implements RequestModel.onSendcodeListener {
    @BindView(R.id.et_login_mobile)
    EditText etLoginMobile;
    @BindView(R.id.et_login_code)
    EditText etLoginCode;
    @BindView(R.id.tv_sendcode)
    NofastClickTextview tvSendcode;
    @BindView(R.id.tv_login)
    NofastClickTextview tvLogin;
    @BindView(R.id.img_wxlogin)
    ImageView imgWxlogin;
    @BindView(R.id.rl_wxlogin)
    RelativeLayout rlWxlogin;
    @BindView(R.id.img_xuanze)
    ImageView imgXuanze;
    @BindView(R.id.tv_xieyi)
    NofastClickTextview tvXieyi;
    @BindView(R.id.et_tuijian)
    EditText etTuijian;
    private String access_token;
    private String openid;

    private RequestModel model;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        BarUtils.setStatusBarForActivity(this);
        rlWxlogin.setVisibility(View.INVISIBLE);

        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        openid = intent.getStringExtra("openid");

        model = new RequestModel();
        model.setOnsendCodeListener(this);

        tvLogin.setText("绑定手机号");
    }


    @OnClick({R.id.img_xuanze, R.id.tv_xieyi, R.id.tv_sendcode, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_xuanze:
                imgXuanze.setSelected(!imgXuanze.isSelected());
                break;
            case R.id.tv_xieyi:
                ActivityUtils.startActivity(UserXieyiActivity.class);
                break;
            case R.id.tv_sendcode:
                String mobile1 = etLoginMobile.getText().toString().trim();
                if (TextUtils.isEmpty(mobile1)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                KeyboardUtils.hideSoftInput(BindPhoneActivity.this);
                sendVerifycode(mobile1);
                break;
            case R.id.tv_login:
                String mobile = etLoginMobile.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                String code = etLoginCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }

                if (!imgXuanze.isSelected()) {

                    ToastUtils.showLong("请勾选用户协议");
                    return;
                }

                String tuijianma = etTuijian.getText().toString().trim();
                getWxinfo(tuijianma, mobile, code, access_token, openid, NetUrl.WXLOGIN);
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVerifycode(final String mobile) {

        model.sendCode(this, mobile);
    }

    private void getWxinfo(final String tuijianma, final String mobile, final String code, final String acctoken, final String openid, final String url) {

        if (!NetworkUtils.isConnected()) {
            ToastUtils.showLong(getString(R.string.neterror));
            return;
        }
        LogUtils.i("accesstoken:" + acctoken);
        LogUtils.i("openid:" + openid);
        Loadingdialog.showAlert(this);
        OkGo.<String>post(url)
                .params("openid", openid)
                .params("access_token", acctoken)
                .params("phone", mobile)
                .params("code", code)
                .params("referee_code", tuijianma)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(final Response<String> response) {
                        Loadingdialog.dismiss();
                        LogUtils.i("绑定手机号:" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {

                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case GlobConstant.REQUESTSUCCESS:
                                        BindPhoneBean bindPhoneBean = GsonUtils.fromJson(response.body(), BindPhoneBean.class);

                                        BindPhoneBean.DataBean data = bindPhoneBean.getData();
                                        String token = data.getRemember_token();
                                        String phone = data.getPhone();
                                        SPUtils.getInstance().put(GlobConstant.TOKEN, token);
                                        SPUtils.getInstance().put(GlobConstant.MOBILE, phone);
                                        EventBus.getDefault().post(new EventBeans("wxLoginSuccess"));
                                        ActivityUtils.startActivity(MainActivity.class);
                                        BindPhoneActivity.this.finish();
                                        break;
                                    default:
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showShort(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Loadingdialog.dismiss();
                        LogUtils.i("微信授权登录错误:" + response.code() + response.body());
                    }
                });

    }


    @Override
    public void start(int s) {
        tvSendcode.setClickable(false);
        tvSendcode.setText(s + "s");
    }

    @Override
    public void end() {
        tvSendcode.setClickable(true);
        tvSendcode.setText("重新发送");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
